package cn.com.tianpeidong.restaurantadmin.project.admin.img.rest;

import cn.com.tianpeidong.restaurantadmin.common.util.file.UploadUtil;
import cn.com.tianpeidong.restaurantadmin.common.util.response.ServerResponse;
import com.alibaba.fastjson.JSONObject;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

/**
 * @author tianpeidong
 * @version 创建时间: 19-3-20 上午11:41
 */
@RestController
@RequestMapping("/img")
public class PubController {

    private static final Logger LOGGER = LoggerFactory.getLogger(PubController.class);

    /**
     * 图片上传接口，图片通过这个接口访问阿里云oss
     * 上传文件的代码可以看
     * @see UploadUtil
     * @param request
     * @param file
     * @return
     */
    @PostMapping
    @RequiresPermissions(value = {"dishes:add", "dishes:edit"}, logical = Logical.OR)
    public ResponseEntity uploadImg(HttpServletRequest request, @RequestBody MultipartFile file) throws URISyntaxException{
        String fileName = file.getOriginalFilename();
        String filePath = request.getSession().getServletContext().getRealPath("restaurant");
        File newFile = new File(filePath);
        if(! newFile.exists()) {
            newFile.mkdirs();
        }
        newFile = new File(filePath, fileName);
        try {
            file.transferTo(newFile);
            String imgUrl = UploadUtil.upload(newFile.getName(), newFile.getAbsolutePath());
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("data", imgUrl);
            return ResponseEntity.ok(jsonObject);
        } catch (IOException e) {
            LOGGER.info("图片上传失败", e);
        }
        return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);

    }
}
